import React, {PureComponent} from 'react';
import {connect} from 'dva';

import {Button, Card, Form, Icon, Input, Modal, Radio, Select, Tooltip, Upload} from 'antd';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './style.less';

const FormItem = Form.Item;
const {Option} = Select;
const {TextArea} = Input;

@connect(state => ({
    shop_category: state.shop_category,
}))
@Form.create()
export default class CategoryEdit extends PureComponent {
    state = {
        thumbUrl: '',
        previewVisible: false,
        previewImage: '',
        content: '',
        fileList: [],
        thumbFile: {},
    }

    componentDidMount() {
        const {match, dispatch} = this.props;

        dispatch({
            type: 'shop_category/queryMenus',
        });
        this.loadService();
    }

    loadService = () => {
        const {match, dispatch} = this.props;
        dispatch({
            type: 'shop_category/fetchService',
            payload: {id: match.params.id},
            callback: (item) => {
                const thumbfile = item.thumb.replace('https://zzbj.kooki.cn', '');
                this.setState({
                    thumbUrl: item.thumb,
                    thumbFile: thumbfile,
                });
            },
        });
    }


    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                values.content = this.state.content;
                values.id = this.props.match.params.id;
                this.props.dispatch({
                    type: 'shop_category/edit',
                    payload: values,
                    callback: () => {
                        this.loadService();
                    },
                });
            }
        });
    }

    handleCancel = () => this.setState({previewVisible: false})

    handlePreview = (file) => {
        console.log(file);
        this.setState({
            previewImage: file.response.data.url,
            previewVisible: true,
        });
    }

    thumbUpload = (info) => {
        if (info.file.status === 'done') {
            const thumbUrl = info.file.response.data.url;
            this.setState({
                thumbUrl,
            });
            return info.file.response.data.file;
        }
    }
    photosChange = ({ fileList }) => {
         this.setState({ fileList });
         return this.state.fileList;
    }

    render() {
        const {shop_category: {categories, item, loading}} = this.props;
        const {getFieldDecorator} = this.props.form;
        const {thumbUrl} = this.state;
        const {previewVisible, previewImage, fileList} = this.state;
        const uploadButton = (
          <div>
            <Icon type="plus" />
            <div className="ant-upload-text">上传图片</div>
          </div>
        );
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 7},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 17},
                md: {span: 14},
            },
        };
        const submitFormLayout = {
            wrapperCol: {
                xs: {span: 24, offset: 0},
                sm: {span: 10, offset: 7},
            },
        };

        return (
          <PageHeaderLayout title="编辑服务" content="编辑零工服务，下列的所有内容均需填写">
            <Card bordered={false}>
              <Form
                onSubmit={this.handleSubmit}
                hideRequiredMark
                style={{marginTop: 8}}
              >
                <FormItem
                  {...formItemLayout}
                  label="分类名称"
                >
                  {getFieldDecorator('name', {
                          rules: [{
                              required: true, message: '请输入分类名称',
                          }],
                          initialValue: item.name,
                      })(
                        <Input placeholder="分类名称" />
                      )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label={
                    <span>
                  类别
                  <em className={styles.optional}>
                      &nbsp;
                    <Tooltip title="选择需要添加到的类别">
                      <Icon type="info-circle-o" style={{marginRight: 4}} />
                    </Tooltip>
                  </em>
                    </span>
                            }
                >
                  {getFieldDecorator('pid', {initialValue: item.pid})(
                    <Select>
                      <Option value={0}>顶级分类</Option>
                      {categories.map((item, i) => (
                        <Option key={`${item.id}-${i}-category`} value={item.id}>{item.name}</Option>
                                    ))}
                    </Select>
                            )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="缩略图"
                >
                  <div className="dropbox">
                    {getFieldDecorator('thumb', {
                                    valuePropName: 'thumb',
                                    getValueFromEvent: this.thumbUpload,
                                    initialValue: this.state.thumbFile,
                                    rules: [{
                                        required: true,
                                        message: '请上传缩略图',
                                    }],
                                })(
                                  <Upload.Dragger
                                    showUploadList={false}
                                    name="file"
                                    action={`/api/upload?token=${sessionStorage.getItem('access_token')}`}
                                  >
                                    {thumbUrl ? <img src={thumbUrl} alt="" className={styles.thumb} /> :
                                    <div>
                                      <p className="ant-upload-drag-icon">
                                        <Icon type="inbox" />
                                      </p>
                                      <p className="ant-upload-text">点击或拖拽上传</p>
                                    </div>}
                                  </Upload.Dragger>
                                )}
                  </div>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="首页显示"
                >
                  {getFieldDecorator('index_show', {initialValue: item.index_show})(
                    <Radio.Group>
                      <Radio value={0}>否</Radio>
                      <Radio value={1}>是</Radio>
                    </Radio.Group>
                            )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="状态"
                >
                  {getFieldDecorator('status', {initialValue: item.status})(
                    <Radio.Group>
                      <Radio value={0}>禁用</Radio>
                      <Radio value={1}>启用</Radio>
                    </Radio.Group>
                            )}
                </FormItem>

                  <FormItem {...submitFormLayout} style={{marginTop: 32}}>
                  <Button type="primary" htmlType="submit" loading={loading}>
                                提交
                  </Button>
                  <Button
                    onClick={() => {
                                    this.props.form.resetFields();
                                }}
                    style={{marginLeft: 8}}
                  >重置
                  </Button>
                </FormItem>
              </Form>
            </Card>
            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
              <img alt="图片预览" style={{width: '100%'}} src={previewImage} />
            </Modal>
          </PageHeaderLayout>
        );
    }
}
